<template>
  <div>
    <div class="app-container">
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryForm" :inline="true">
          <!-- StartDate  EndDate -->
          <el-form-item prop="keywords">
            <el-input v-model="queryForm.keywords" placeholder="请输入关键字" clearable style="width: 200px" />
            <el-button type="primary" style="margin-left: 0; border-radius: 0" @click="handleQuery"> 搜索 </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--右边数据-->
      <div class="search-container">
        <el-row :gutter="20">
          <!-- <el-col :span="24" :offset="0">
            <el-button type="success" @click="handleAdd()"><i-ep-plus />新增</el-button>

            <el-button type="primary" :loading="download_loading" @click="download()"><i-ep-download />导出</el-button>
          </el-col> -->
          <el-col :span="24" :offset="0" style="padding-top: 15px">
            <el-table
              ref="tableRef"
              v-loading="tableDataLoading"
              :data="tableData"
              row-key="projectId"
              style="width: 100%"
              @expand-change="loadTable"
              @selection-change="handleSelectionChange"
            >
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column type="expand" style="display: flex; margin: auto">
                <template #default="props">
                  <el-table
                    v-loading="loadings.get(props.row.projectId)"
                    :data="dic.get(props.row.projectId)"
                    row-key="groupId"
                    style="width: 80%; display: flex; margin: auto"
                    align="center"
                  >
                    <!-- <el-table-column type="selection" width="55" align="center" /> -->
                    <el-table-column label="班组名称" prop="name" min-width="110" />
                    <el-table-column
                      label="管理部班组"
                      prop="isManagerGroup"
                      min-width="120"
                      :formatter="(row) => (row.isManagerGroup ? '是' : '否')"
                    />
                    <el-table-column label="参建单位名称" prop="corpName" min-width="150" />
                    <el-table-column label="班组长姓名" prop="groupMemberLeader" min-width="110" />
                    <el-table-column label="联系电话" prop="linkMobile" min-width="110" />
                    <el-table-column label="进场日期" prop="startDate" min-width="100" />
                    <el-table-column label="离场日期" prop="endDate" min-width="100" />
                    <el-table-column fixed="right" label="操作" align="center" min-width="100">
                      <template #default="scope">
                        <!-- <el-button type="primary" link @click="getInOrOut('in', scope.row.groupId)">一键进场</el-button>
                        <el-button type="primary" link @click="getInOrOut('out', scope.row.groupId)"
                          >一键离场</el-button
                        >
                        <el-button type="primary" link @click="openDialog(scope.row.groupId)">编辑</el-button> -->
                        <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
                        <!-- <el-button type="primary" link @click.stop="handleDelete(scope.row.groupId)"> 删除 </el-button> -->
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column label="项目编号" prop="prjNum" />
              <el-table-column label="项目名称" prop="name" />
              <el-table-column label="建设单位" prop="buildCorpName" />
              <el-table-column label="项目种类" prop="fundsSourceName" />
              <el-table-column label="项目类型" prop="categoryName" />
              <el-table-column label="建设性质" prop="propertyNumName" />
              <el-table-column label="班组数量" prop="totalGroupCount" />
            </el-table>
            <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryForm.pageIndex"
              v-model:limit="queryForm.pageSize"
              @pagination="handleQuery"
            />
          </el-col>
        </el-row>
      </div>
    </div>

    <!--编辑弹窗-->
    <el-dialog
      v-model="dialog.visible"
      v-loading="dialog.loading"
      :title="dialog.title"
      width="500"
      class="system"
      draggable
      @close="closeDialog"
    >
      <el-form ref="groupFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="所属项目" prop="projectName">
          <el-input v-model="formData.projectName" disabled placeholder="请选择所属项目" />
        </el-form-item>
        <el-form-item label="班组名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入班组名称" />
        </el-form-item>
        <el-form-item label="参建企业" prop="corpId">
          <el-input v-model="formData.corpName" readonly placeholder="请选择参建企业" class="input300 inputred">
          </el-input>
          <el-button type="primary" style="position: absolute; right: 0px" plain @click="openCorpSelect">
            <el-icon> <OfficeBuilding /> </el-icon>&nbsp;选择
          </el-button>
        </el-form-item>
        <el-form-item label="管理部班组" prop="isManagerGroup">
          <el-select v-model="formData.isManagerGroup" placeholder="请选择" style="width: 100%">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="进场日期" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择进场日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="离场日期" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled="!formData.startDate"
            type="date"
            placeholder="请选择离场日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--选择企业-->
    <SelectCorp
      v-if="dialogSelectCorp.visible"
      :dialog-select-corp="dialogSelectCorp"
      :corp-list-query="'common'"
      @corp-send-close="corpSendClose"
    ></SelectCorp>
    <detail :dialog-preview="dialogPreview" :data-info="dataInfo" @send-close="sendClose"></detail>
  </div>
</template>
<script lang="ts" setup>
/**引入文件**/
import detail from "./groupDetail.vue";
import { downloadFile } from "@/utils";
import { projectGroupForm } from "@/api/worker/types";
import {
  QueryProjectPage,
  downloadGroups,
  QueryProjectGroupPage,
  getGroupForm,
  updateGroup,
  addGroup,
  inGroups,
  outGroups,
  deleteGroups,
} from "@/api/worker/index";
import SelectCorp from "@/views/manager/common/SelectCorp/index.vue";
// const loading = ref(false);
//这是列表数据
const tableData = ref<any[]>([]);
const dic = ref(new Map());
const queryForm = reactive({
  pageIndex: 1,
  pageSize: 10,
  keywords: "",
} as any);
const total = ref(0);
const loadings = ref(new Map());
const tableDataLoading = ref(false);
const ids = ref<number[]>([]);
const selectedProjects = ref<any[]>([]);
const groupFormRef = ref();
const download_loading = ref(false);
const dialog = reactive({
  visible: false,
  loading: false,
  title: "新增班组",
});
const dialogMember = reactive<DialogOption>({
  visible: false,
});

const dialogPreview = reactive<DialogOption>({
  visible: false,
  title: "详情",
});
const dataInfo = ref<any>({});
const formData = reactive<projectGroupForm>({});
const dialogSelectCorp = reactive({
  visible: false,
  title: "选择企业",
  id: 0,
  corpId: 0,
});
const tableRef = ref();

//生命周期事件
onMounted(async () => {
  handleQuery();
});

const handleDetail = (row: any) => {
  dataInfo.value = row;
  dialogPreview.title = "详情";
  dialogPreview.id = row.groupId;
  dialogPreview.visible = true;
};

const sendClose = (needRefresh: boolean) => {
  dialogPreview.visible = false;
  if (needRefresh) {
    handleQuery();
  }
};

const handleQuery = function () {
  tableData.value.forEach((row: any) => {
    tableRef.value.toggleRowExpansion(row, false);
    tableRef.value.toggleRowSelection(row, false);
  });
  tableDataLoading.value = true;
  QueryProjectPage(queryForm)
    .then((res) => {
      if (res.type === 0) {
        if (res.success) {
          tableData.value = res.data.list;
          queryForm.pageIndex = res.data.pageNum;
          queryForm.pageSize = res.data.pageSize;
          total.value = res.data.total;
        } else {
        }
      } else {
      }
    })
    .finally(() => {
      tableDataLoading.value = false;
    });
};

function handleSelectionChange(selection: any) {
  selectedProjects.value = selection;
}

//加载成员信息
const loadTable = function (row: any, expandRows: any) {
  loadings.value.set(row.projectId, true);
  QueryProjectGroupPage(row.projectId).then((res) => {
    if (res.success === true) {
      dic.value.set(row.projectId, res.data.list);
    }
    loadings.value.set(row.projectId, false);
  });
};

//删除
function handleDelete(id?: number) {
  const groupids = [id || ids.value].join(",");
  if (!groupids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      tableDataLoading.value = true;
      deleteGroups(groupids)
        .then((resp) => {
          if (resp.success === true) {
            ElMessage.success(resp.msg);
            handleQuery();
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (tableDataLoading.value = false));
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消！",
      });
    });
}

//新增班组
const handleAdd = function () {
  if (selectedProjects.value.length == 0 || selectedProjects.value.length > 1) {
    ElMessage.warning("请选择一条数据");
    return;
  }
  formData.projectId = selectedProjects.value[0].projectId;
  formData.projectName = selectedProjects.value[0].name;
  openDialog();
};

//编辑弹窗
function openDialog(id?: number) {
  dialog.visible = true;
  dialog.title = "编辑班组";
  if (id) {
    getGroupForm(id).then((res) => {
      Object.assign(formData, res.data);
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 重置表单
 */
function resetForm() {
  groupFormRef.value.resetFields();
  groupFormRef.value.clearValidate();
  formData.corpId = undefined;
  formData.corpName = "";
  formData.groupId = undefined;
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/* 打开企业选择 */
function openCorpSelect() {
  dialogSelectCorp.visible = true;
}
function corpSendClose(data: any) {
  if (!data) {
    dialogSelectCorp.visible = false;
    formData.corpId = undefined;
    formData.corpName = undefined;
    return;
  }
  formData.corpId = data.corpId;
  formData.corpName = data.name;
  dialogSelectCorp.visible = false;
}

//一键进出场
function getInOrOut(type: string, id?: number) {
  const groupids = [id].join(",");
  if (type === "in") {
    ElMessageBox.confirm("确认一键进场", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        tableDataLoading.value = true;
        inGroups(groupids)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              tableData.value.forEach((row: any) => {
                tableRef.value.toggleRowExpansion(row, false);
                tableRef.value.toggleRowSelection(row, false);
              });
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (tableDataLoading.value = false));
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消！",
        });
      });
  } else if (type === "out") {
    ElMessageBox.confirm("确认一键离场", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        tableDataLoading.value = true;
        outGroups(groupids)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              tableData.value.forEach((row: any) => {
                tableRef.value.toggleRowExpansion(row, false);
                tableRef.value.toggleRowSelection(row, false);
              });
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (tableDataLoading.value = false));
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消！",
        });
      });
  }
}

//验证
const rules = reactive({
  name: [{ required: true, message: "请输入班组名称", trigger: "blur" }],
  corpId: [{ required: true, message: "请选择参建单位", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择进场日期", trigger: "blur" }],
  endDate: [{ required: true, message: "请选择离场日期", trigger: "blur" }],
});
const rulesMember = reactive({
  newGroupId: [{ required: true, message: "请选择更换班组", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择进场日期", trigger: "blur" }],
  endDate: [{ required: true, message: "请选择离场日期", trigger: "blur" }],
});

//更换人员所在班组提交

function download() {
  if (selectedProjects.value.length == 0 || selectedProjects.value.length > 1) {
    ElMessage.warning("请选择一条数据");
    return;
  }
  download_loading.value = true;
  downloadGroups(selectedProjects.value[0].projectId).then((response: any) => {
    if (!response.headers["content-disposition"]) {
      const decoder = new TextDecoder("utf-8");
      const resp = decoder.decode(response.data);
      let objResp = JSON.parse(resp);
      ElMessage.error(objResp.msg);
      download_loading.value = false;
      return;
    }

    downloadFile(response);
    download_loading.value = false;
  });
}

/**
 * 新增编辑表单提交
 */
function handleSubmit() {
  groupFormRef.value.validate((valid: any) => {
    if (valid) {
      dialog.loading = true;
      tableDataLoading.value = true;
      const groupId = formData.groupId;
      if (groupId) {
        updateGroup(groupId, formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog();
              handleQuery();
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => {
            tableDataLoading.value = false;
            dialog.loading = false;
          });
      } else {
        addGroup(formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog();
              handleQuery();
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => {
            tableDataLoading.value = false;
            dialog.loading = false;
          });
      }
    }
  });
}
</script>
<style lang="scss" scoped>
.el-menu {
  border-right: 0 !important;
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: #3b98f7 !important;
  color: #fff;
  fill: #fff !important;
}
:deep(.el-tree-node__content) {
  color: #000;
}
.left {
  width: 20%;
  display: flex;
  float: left;
  min-height: 680px;
}

.right {
  width: 79.5%;
  display: flex;
  float: right;
  min-height: 680px;
}

.icon {
  margin-right: 10px;
}
</style>
